package org.jiangwei.cmput696.entitylinking;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.StringReader;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.Charset;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

public class Helper {

	public static NodeList extractXMLNodeList(File file, String nodeName)
			throws QueryParsingException {
		
		String xmlStr = getRawText(file).replaceAll("&(?!amp;)", "&amp;");
		
		DocumentBuilder db = createDocumentBuilder();
		Document doc;
		try {
			doc = db.parse(new InputSource(new StringReader(xmlStr)));
		} catch (SAXException e) {
			throw new QueryParsingException("The XML file may be malformed.", e);
		} catch (IOException e) {
			throw new QueryParsingException("Failed to read the XML file.", e);
		}
		doc.getDocumentElement().normalize();

		NodeList nodeLst = doc.getElementsByTagName(nodeName);
		return nodeLst;
	}


	public static String getRawText(File file) throws QueryParsingException {
		FileInputStream stream = null;
		try {
			stream = new FileInputStream(file);
			FileChannel fc = stream.getChannel();
			MappedByteBuffer bb = fc.map(FileChannel.MapMode.READ_ONLY, 0,
					fc.size());
			return Charset.defaultCharset().decode(bb).toString();
		} catch (IOException e) {
			throw new QueryParsingException(
					"Failed to read the queried document.", e);
		} finally {
			if (stream != null) {
				try {
					stream.close();
				} catch (IOException e) {
				}
			}
		}
	}
	public static DocumentBuilder createDocumentBuilder()
			throws QueryParsingException {
		DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
		DocumentBuilder db;
		try {
			db = dbf.newDocumentBuilder();
		} catch (ParserConfigurationException e) {
			throw new QueryParsingException(
					"Failed to create the document builder.", e);
		}
		return db;
	}

	/**
	 * Read the string value of a child.
	 * 
	 * @param parentElement
	 * @param elementName
	 * @return
	 */
	public static String readNodeChild(Element parentElement, String elementName) {
		NodeList list = parentElement.getElementsByTagName(
				elementName);
		if (list.getLength() == 0) return null;
		Element fstNmElmnt = (Element) list.item(0);
		NodeList fstNm = fstNmElmnt.getChildNodes();
		if (fstNm.getLength() == 0) return null;
		return ((Node) fstNm.item(0)).getNodeValue();
	}
	
	public static void main(String[] args) {
		String str = "sdasdasa&amp;adas&dasdasa";
		str = str.replaceAll("&(?!amp;)", "&amp;");
		System.out.println(str);
	}
}
